<template>
    <section>

        <!--高级查询form表单-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="searchForm">
                <el-form-item>
                    <el-input v-model="searchForm.name" placeholder="服务名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="searchForm.state" clearable  placeholder="请选择状态">
                        <el-option label="上架" value="1"></el-option>
                        <el-option label="下架" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="loadProducts">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                    <el-button type="primary" :disabled="this.sels.length===0" @click="onSale">上架</el-button>
                    <el-button type="primary" :disabled="this.sels.length===0" @click="offSale">下架</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--服务列表-->
        <el-table :data="products" v-loading="listLoading"   @selection-change="selsChange" style="width: 100%;">
            <!--复选框-->
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" label="序号">
            </el-table-column>
            <el-table-column prop="name" label="服务名">
            </el-table-column>
            <el-table-column prop="saleprice" label="售价">
            </el-table-column>
            <el-table-column prop="onsaletime" label="上架时间">
            </el-table-column>
            <el-table-column prop="offsaletime" label="下架时间">
            </el-table-column>
            <el-table-column prop="state" label="状态">
                <!--参考下面【操作】代码，可以获取每行的数据，根据每行的状态数据判断显示上架还是下架-->
                <template scope="scope">
                    <span v-if="scope.row.state==1" style="color: green">上架</span>
                    <span v-if="scope.row.state==0" style="color: red">下架</span>
                </template>
            </el-table-column>
            <el-table-column prop="costprice" label="成本价">
            </el-table-column>
            <el-table-column prop="createtime" label="创建时间">
            </el-table-column>
            <el-table-column prop="salecount" label="销量">
            </el-table-column>
            <el-table-column label="操作" >
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--
            新增/编辑 界面
             :title 弹出框标题
             addFormVisible 是否弹出框提
             :rules: 定义校验规则的
             ref="ruleForm"简单理解就是form表单的id一样
        -->
        <el-dialog :title="title"  v-model="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" :rules="addFormRules" ref="addForm"  label-width="80px" >
                <!--prop="name"：校验的字段-->
                <el-form-item label="服务名" prop="name">
                    <el-input v-model="addForm.name"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="成本价">
                    <el-input v-model="addForm.costprice"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="销售价">
                    <el-input v-model="addForm.saleprice"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item prop="resources" label="图片上传">
                    <el-upload
                            class="upload-demo"
                            action="/api/fastDfs"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :on-success="handleSuccess"
                            :file-list="fileList"
                            list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="服务简介">
                    <quill-editor v-model="addForm.intro" :options="editorOption"></quill-editor>
                </el-form-item>
                <el-form-item label="预约须知">
                    <quill-editor v-model="addForm.orderNotice" :options="editorOption"></quill-editor>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addSubmit" >提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import {removeUser} from "../../api/api";
    /* 引入富文本编辑器对应的插件 js和css */
    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import quillConfig from "../../common/js/quill-config"
    export default {
        components: {
            quillEditor
        },
        data() {
            return {
                editorOption: quillConfig,
                //弹出框标题
                title: "",
                //是否弹出窗体，默认不弹出
                addFormVisible: false,
                //弹出框中form表单对应的data数据
                addForm: {
                    id:"",
                    //服务名
                    name: "",
                    //成本价
                    costprice: "",
                    //销售价
                    saleprice: "",
                    //定义一个资源来装图片路径
                    resources:"",
                    //服务简介
                    intro: "",
                    //预约须知
                    orderNotice: ""
                },
                // rules校验规则
                addFormRules: {
                    name: [
                        {required: true, message: '服务名必填！!', trigger: 'blur'}
                    ]
                },
                //附件回显数据：图片列表
                fileList:[],
                //高级查询的form表单
                searchForm:{
                    name:"",
                    state:""
                },
                //服务分页列表
                products:[],
                //当前页
                currentPage:1,
                //每页条数
                pageSize:10,
                //总条数
                total: 0,
                // 加载框
                listLoading:false,
                //列表选中列，选中复选框对应的地址
                sels: [],
                dfsUrl:"http://81.70.161.93:8888"
            }
        },
        methods:{
                //图片相关的三个方法
                handleSuccess(response, file, fileList){
                    console.log("===========")
                    console.log("response",response);
                    console.log("file",file);
                    console.log("fileList",fileList);

                    /*
                    * 这里有一个bug，当我们点击编辑的时候，上传图片会报错【暂时先不处理，截图：96和97】
                    * 如果点击的是编辑按钮，那么回显的图片和新增的图片数据格式是不一样的。
                    * 可以根据是否有response来判断，新增的话是有这个的，编辑的话是直接就是url
                    * 第一步：判断fileList的长度有值的话，获取url
                    * 第二步：长度灭有值的话，获取response.resultObj
                    * */

                    /*console.log("回显的url",fileList[0].url);
                    console.log("fileList的长度",fileList.length);

                    if(fileList.length != 0){
                        for(let i = 0; i < fileList.length; i++){
                            let file = fileList[i];
                            this.addForm.resources = this.addForm.resources+","+file.url;
                        }
                    }*/

                    // 可能上传多张图片
                    for(let i = 0; i < fileList.length; i++){
                        // 获取具体的file对象
                        let fileObj = fileList[i];
                        console.log("fileObj",fileObj);
                        // 判断如果有值，表示新增
                        if(fileObj.response){
                            // 新增是这样获取url地址的
                            let url = fileObj.response.resultObj;
                            if(i == 0){
                                this.addForm.resources = url;
                            } else {
                                this.addForm.resources = this.addForm.resources+","+url;
                            }
                        } else {
                            // 这里就是编辑了，回显的url是带有ip地址的，直接获取url就可以
                            console.log("fileObj.url",fileObj.url);
                            // 获得带有ip的url地址
                            let url = fileObj.url;
                            // 我们不需要ip，所以需要进行切割
                            if(i == 0){
                                // http://81.70.161.93:8888/group1/M00/00/00/rBUACGIIgACABhp4AAH3HBuvw60706.jpg
                                // 通过截取ip地址ide长度获取后面的值
                                this.addForm.resources = url.substring(this.dfsUrl.length);
                            } else {
                                this.addForm.resources = this.addForm.resources+","+url.substring(this.dfsUrl.length);
                            }
                        }

                        /* // 判断指定的字符串是否存在，如果存在，它是大于等于的
                         if(fileObj.indexOf(this.dfsUrl) >= 0){

                         } else {
                             // 如果不存在，说明之前没有保存图片
                             let url = fileObj.response.resultObj;
                             if(i == 0){
                                 this.addForm.resources = url;
                             } else {
                                 this.addForm.resources = this.addForm.resources+","+url;
                             }
                         }*/


                    }
                    console.log("this.addForm.resources",this.addForm.resources);
                },
                handleRemove(file, fileList) {
                    // 删除也是一样的操作，判断是否有 response
                    let url = "";
                    if(file.response){
                        // 新增的话是通过response来获取值
                        url = file.response.resultObj;
                    } else {
                        // 修改的话是通过url来获取值
                        url = file.url.substring(this.dfsUrl.length);

                    }

                    // 先通过file把其作为参数传递到后台进行删除，然后再重新设置resources的值
                    //let param = {"url" : url};
                    console.log("删除请求的参数param",url);
                    // 请求服务器删除文件图片数据
                    this.$http.delete("/fastDfs/?path="+url).then(res=>{
                        // 如果删除成功
                        if(res.data.success){
                            // 如果没有图片，则给资源设置路径为空
                            if(fileList.length == 0){
                                this.addForm.resources = "";
                                this.$message({
                                    message: '删除成功!',
                                    type: 'success'
                                });
                            }
                            // 否则循环路径，拼接resources的值
                            for(let i = 0; i < fileList.length; i++){
                                // 获取具体的file对象
                                let fileObj = fileList[i];
                                if(fileObj.response){
                                    // 如果有值，表示是新增的
                                    // 单张图片的url
                                    let url = fileObj.response.resultObj;
                                    if(i == 0){
                                        this.addForm.resources = url;
                                    } else {
                                        this.addForm.resources = this.addForm.resources+","+url;
                                    }
                                } else {
                                    // 单张图片的url
                                    let url = fileObj.url;
                                    if(i == 0){
                                        this.addForm.resources = url.substring(this.dfsUrl.length);
                                    } else {
                                        this.addForm.resources = this.addForm.resources+","+url.substring(this.dfsUrl.length);
                                    }
                                }

                            }
                        }else {
                            this.$message({
                                message: '删除失败!',
                                type: 'error'
                            });
                        }
                    })
                },
                handlePreview(file) {
                    console.log(file);
                },
            //新增弹出窗体
            handleAdd(){
                //设置标题
                this.title = "新增";
                //重置
                if(this.$refs["addForm"]){
                    this.$refs["addForm"].resetFields();
                }
                //清空form表单
                for(var k in this.addForm){
                    this.addForm[k] = "";
                }
                //清空图片列表
                this.fileList = [];
                //显示弹出框
                this.addFormVisible = true;
            },
            //上架
            onSale(){
                //提示确认信息
                this.$confirm('您确认上架吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.$http.patch("/product/batchOnSale",this.sels).then(res=>{
                        let {success, msg} = res.data;
                        if(success){
                            this.$message({
                                message: '上架成功',
                                type: 'success'
                            });
                            //刷新界面
                            this.loadProducts();
                        }else{
                            this.$message.error('错了哦，这是一条错误消息');
                        }
                    })
                }).catch(() => {

                });
            },
            //下架
            offSale(){},
            // 选中复选框触发次函数，vals表示选中的值(行值)
            selsChange(vals){
                //console.debug("选中的行",vals);
                this.sels = vals;
                //console.debug("选中的行",this.sels);
            },
            //加载服务分页列表
            loadProducts(){
                //显示加载框
                this.listLoading = true;
                //前端传递的分页参数(当前页，每页条数)
                let param = {
                    "currentPage": this.currentPage, "pageSize": this.pageSize,
                    "name":this.searchForm.name,"state":this.searchForm.state
                };
                //请求url地址，并且传递参数
                this.$http.patch("/product",param).then(res=>{
                    //关闭加载框
                    this.listLoading = false;
                    let {total,result} = res.data;
                    //返回分页列表
                    this.products = result;
                    //返回总条数
                    this.total = total;
                })
            },
            //批量删除按钮
            batchRemove(){
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.$http.patch("/product/batchRemove",this.sels).then((res => {
                        let {success,msg} = res.data;
                        if(success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            //刷新界面
                            this.loadProducts();
                        }else{
                            this.$message.error('错了哦，这是一条错误消息');
                        }
                    }));
                }).catch(() => {

                });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.$http.delete("/product/"+row.id).then((res=>{
                        //console.debug(res);
                        let {success,msg} = res.data;
                        if(success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            //刷新界面
                            this.loadProducts();
                        }else{
                            this.$message.error(msg);
                        }
                    }));
                }).catch(() => {

                });
            },
            //页码发生改变的时候触发此函数     参数val，表示页码
            handleCurrentChange(val){
                //重新设置当前页
                this.currentPage = val;
                //刷新页面
                this.loadProducts();
            },
            //提交按钮注册事件
            addSubmit(){
                console.debug(this.addForm);
                // 创建服务详情对象
                let productDetail = {"intro":this.addForm.intro,"orderNotice":this.addForm.orderNotice};
                // 添加服务详情对象
                this.addForm.productDetail = productDetail;
                //必须验证通过之后，才执行if语句中的内容
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$http.put("/product", this.addForm).then((res => {
                            let {success, msg} = res.data;
                            if(success){
                                //刷新列表
                                this.loadProducts();
                                //关闭弹出框
                                this.addFormVisible = false;
                            }else{
                                this.$message.error(msg);
                            }
                        }));
                    }
                });
            },
            //编辑弹出框
            handleEdit(index,row){
                //修改标题
                this.title = "修改";
                //能解决大部分的属性
                for(var k in this.addForm){
                    this.addForm[k] = row[k];
                }
                console.debug(row);
                // 行数据中的服务详情有数据则回显
                if(row.productDetail){
                    //对于特定属性，我们手动赋值
                    this.addForm.intro = row.productDetail.intro;
                    this.addForm.orderNotice = row.productDetail.orderNotice;
                }
                // 行数据中的图片资源有数据的话进行回显，将图片地址赋值给 fileList
                if(row.resources){
                    //获取图片资源
                    var resources = row.resources;
                    //图片资源准备做回显的
                    this.fileList = [];
                    //把图片分割成数组
                    var resourcesArr = resources.split(",");
                    for(var i=0;i<resourcesArr.length;i++){
                        //this.fileList.push({"url":resourcesArr[i]});
                        this.fileList.push({"url":"http://81.70.161.93:8888"+resourcesArr[i]});
                    }
                }

                //弹出窗体
                this.addFormVisible = true;
            }
        },
        mounted() {
            //加载服务列表(分页)
            this.loadProducts();
        }
    }
</script>